<?php

class DefaultController extends Controller {

    protected $_model;
    protected $_arrParam;
    protected $_actionMain;
    protected $_namespace;
    protected $pages = 7;

    public function init() {
        parent::init();
        $this->_arrParam['controller'] = Yii::app()->getController()->getId();
        $this->_actionMain = $this->_arrParam['controller'] . '/index';
        $this->_namespace = $this->_arrParam['controller'];
        $ssFilter = Yii::app()->session[$this->_namespace];
        $this->_arrParam['ssFilter']['select_date'] = $ssFilter['select_date'];
        $this->_arrParam['ssFilter']['date_from'] = $ssFilter['date_from'];
        $this->_arrParam['ssFilter']['date_to'] = $ssFilter['date_to'];
    }

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('login'),
                'users' => array('?'),
            ),
            array('allow',
                'actions' => array('index', 'logout', 'config', 'addConfig', 'updateConfig', 'deleteConfig', 'writeConfig'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        $model = new Events;
        $ssFilter = $this->_arrParam['ssFilter'];
        $ssFilter = array_filter($ssFilter);
        $begin_date = date('Y-m-d', strtotime('-1 month'));
        $end_date = date('Y-m-d');
        $date_from = !empty($ssFilter['date_from']) ? date_create($ssFilter['date_from']) : date_create(date('Y-m-d', strtotime('-1 month')));
        $date_to = date_create($end_date);
        $interval = $date_from->diff($date_to);
        $num = $interval->days + 1;
        $criteria_events = new CDbCriteria;
        $criteria_events->select = 'date(posteddate) as date, COUNT(id) as mem_count';
        $criteria_events->group = 'date(posteddate)';

        if (!empty($ssFilter)) {
            if (!empty($ssFilter['date_from'])) {
                $date = $ssFilter['date_from'];
                $criteria_events->condition = " DATEDIFF(date(posteddate),'" . $date . "') >= 0";
            }
            if (!empty($ssFilter['date_to'])) {
                $date = $ssFilter['date_to'];
                $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date . "') <= 0";
            }
            if (!empty($ssFilter['date_from']) && !empty($ssFilter['date_to'])) {
                $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $ssFilter['date_from'] . "') >= 0 AND DATEDIFF(date(posteddate),'" . $ssFilter['date_to'] . "') <= 0";
            }
            if (empty($ssFilter['date_from']) && empty($ssFilter['date_to'])) {
                $date = date('Y-m-d', strtotime('-1 month'));
                $end_date = date('Y-m-d');
                $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date . "') >= 0 AND DATEDIFF(date(posteddate),'" . $end_date . "') <= 0";
                //DATEDIFF(cs_orders.create_date,'" . $date_end . "') <= 0
            }
        } else {
            $date = date('Y-m-d', strtotime('-1 month'));
            $end_date = date('Y-m-d');
            $criteria_events->condition = "DATEDIFF(date(posteddate),'" . $date . "') >= 0 AND DATEDIFF(date(posteddate),'" . $end_date . "') <= 0";
        }
        $item_event = Events::model()->findAll($criteria_events);
        $criteria = new CDbCriteria;
        $criteria->select = 'date(createddate) as date, COUNT(id) as mem_count';
        $criteria->group = 'date(createddate)';

        if (!empty($ssFilter)) {
            if (!empty($ssFilter['date_from'])) {
                $date = $ssFilter['date_from'];
                $criteria->condition = " DATEDIFF(date(createddate),'" . $date . "') >= 0";
            }
            if (!empty($ssFilter['date_to'])) {
                $date = $ssFilter['date_to'];
                $criteria->condition = "DATEDIFF(date(createddate),'" . $date . "') <= 0";
            }
            if (!empty($ssFilter['date_from']) && !empty($ssFilter['date_to'])) {
                $criteria->condition = "DATEDIFF(date(createddate),'" . $ssFilter['date_from'] . "') >= 0 AND DATEDIFF(date(createddate),'" . $ssFilter['date_to'] . "') <= 0";
            }
            if (empty($ssFilter['date_from']) && empty($ssFilter['date_to'])) {
                $date = date('Y-m-d', strtotime('-1 month'));
                $end_date = date('Y-m-d');
                $criteria->condition = "DATEDIFF(date(createddate),'" . $date . "') >= 0 AND DATEDIFF(date(createddate),'" . $end_date . "') <= 0";
                //DATEDIFF(cs_orders.create_date,'" . $date_end . "') <= 0
            }
        } else {
            $date = date('Y-m-d', strtotime('-1 month'));
            $end_date = date('Y-m-d');
            $criteria->condition = "DATEDIFF(date(createddate),'" . $date . "') >= 0 AND DATEDIFF(date(createddate),'" . $end_date . "') <= 0";
        }
        $item = Member::model()->findAll($criteria);
        $date_from = !empty($ssFilter['date_from']) ? date_create($ssFilter['date_from']) : date_create(date('Y-m-d', strtotime('-1 month')));
        $date_to = date_create($end_date);
        $interval = $date_from->diff($date_to);
        $num = $interval->days + 1;
        for ($i = 1; $i < $num; $i++) {
            $date1 = $item[0]['date'];
            $tomorrow = date('Y-m-d', strtotime($date1 . "+$i days"));
            $arr[$tomorrow] = 0;
        }
        if(!isset($arr))
            $arr= array();
        $this->render('index', array(
            'model' => $model,
            'item' => $item,
            'item_event'=>$item_event,
            'arr' => $arr,
            'numdays' => $num
        ));
    }

    public function actionLogin() {
        $this->layout = '//layouts/defaultLogin';
        $model = new LoginForm;

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            if ($model->validate() && $model->login()) {
                $this->redirect(array('/Dashboard/default/index'));
            }
        }

        $this->render('login', array(
            'model' => $model
        ));
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionConfig() {
        $model = new Configs;
        $dataProvider = new CActiveDataProvider('Configs', array(
            'sort' => array(
                'defaultOrder' => 'id ASC',
            ),
            'pagination' => array(
                'pageSize' => 10,
                'pageVar' => 'page',
            ),
                )
        );

        $this->render('config', array(
            'dataProvider' => $dataProvider,
            'model' => $model
        ));
    }

    public function actionAddConfig() {
        $model = new Configs;
        if (isset($_POST['Configs'])) {
            $model->attributes = $_POST['Configs'];
            $model->posteddate = $model->updatedate = date('Y-m-d H:i:s');
            if ($model->save()) {
                $this->redirect(array('/Dashboard/default/config'));
            }
        }
    }

    public function actionUpdateConfig($id) {
        $model = Configs::model()->findByPk($id);

        if (isset($_POST['Configs'])) {
            $model->attributes = $_POST['Configs'];
            $model->updatedate = date('Y-m-d H:i:s');
            if ($model->save()) {
                $this->redirect(array('/Dashboard/default/config'));
            }
        }

        $this->render('updateConfig', array(
            'model' => $model
        ));
    }

    public function actionDeleteConfig($id) {
        $model = Configs::model()->findByPk($id)->delete();

        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    public function actionWriteConfig() {
        $model = Configs::model()->findAll();

        $fp = fopen(CONFIG_MAIN_FILE, "w");
        fwrite($fp, "<?php" . PHP_EOL);
        fclose($fp);
        foreach ($model as $x => $data) {
            if ($x >= 0) {
                file_put_contents(CONFIG_MAIN_FILE, "define('$data->key', '" . str_replace("'", "\'", $data->value) . "');" . PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents(CONFIG_MAIN_FILE, "define('$data->key', '" . str_replace("'", "\'", $data->value) . "');" . PHP_EOL);
            }
        }
        /*
          foreach ($model as $data) {
          fwrite($fp, mb_convert_encoding ("define('$data->key', '".str_replace("'", "\'", $data->value)."');".PHP_EOL, 'UTF-8'));
          }
          fclose($fp);
         */
        $this->redirect(array('/Dashboard/default/config'));
    }
    public function actionFilters() {
            $ssFilter = Yii::app()->session;
            if( isset( $_GET['type'] ) && isset( $_GET['key'] ) ){
                if( $_GET['type'] == 'search' && $_GET['key'] == 1 ){
                    if( !empty( $_POST['date_from'] ) )
                        $arr['date_from'] = $_POST['date_from'];
                    else
                        $arr['date_from'] = '';
                    if( !empty( $_POST['date_to'] ) )
                        $arr['date_to'] = $_POST['date_to'];
                    else
                        $arr['date_to'] = '';
                    if( !empty( $_POST['select_date'] ) )
                        $arr['select_date'] = $_POST['select_date'];
                    else
                        $arr['select_date'] = '';
                    if( !empty( $_POST['date_to'] ) && !empty( $_POST['date_to'] ) ){
                        if( strtotime($_POST['date_from']) > strtotime($_POST['date_to']) ){
                            $arr['date_from'] = '';
                            $arr['date_to'] = '';
                        }else{
                        $arr['date_from'] = $_POST['date_from'];
                        $arr['date_to'] = $_POST['date_to'];
                        }
                    }
                }
                else
                {
                        $arr['date_from'] = '';
                        $arr['date_to'] = '';
                        $arr['select_date'] = '';
                }
                $ssFilter[$this->_namespace] = $arr;
            }
            $this->redirect(array('/Dashboard/default/index'));
        }

}